﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ControlPresupuesto
{
    public partial class FrmRegistrosContablesINFOR_Importar : Form
    {
        private int numeroIntentosConsultarRegistrosInfor = 4;
        private int MilisegundosDeEspera = 1000;

        public FrmRegistrosContablesINFOR_Importar()
        {
            InitializeComponent();            
        }

        private void FrmRegistrosContablesINFOR_Importar_Load(object sender, EventArgs e)
        {   
            //// TODO: esta línea de código carga datos en la tabla 'controlPresupuestoDataSet.spRegistroINFORCabecera' Puede moverla o quitarla según sea necesario.
            //this.spRegistroINFORCabeceraTableAdapter.Fill(this.controlPresupuestoDataSet.spRegistroINFORCabecera);

            //-- Blanquear Campos
            Utils.get().blanquearCampos(this);
            
            //--- Muestro siempre por defecto el periodo pasado
            this.periodoDateTimePicker.Value = DateTime.Now.AddMonths(-1);                
        }

        private void cancelarButton_Click(object sender, EventArgs e)
        {
            this.FrmRegistrosContablesINFOR_Importar_Load(null, null);
        }

        private void guardarButton_Click(object sender, EventArgs e)
        {
            int i = 0;
            string xml = string.Empty;
    
            if (this.ObservacionesTextBox.Text.Trim().Equals(string.Empty))
            {
                MessageBox.Show("Debe digitar las observaciones");
                this.ObservacionesTextBox.Focus();
                return;
            }

            try
            {
                Cursor.Current = Cursors.WaitCursor;

                //--- verifico si los registros correspondientes al periodo en cuestion puedens er agregados.
                //---- (si NO se presenta algun error entonces el periodo puede ser agregado.)
                this.spRegistroINFORCabeceraTableAdapter.FillBy(
                    this.controlPresupuestoDataSet.spRegistroINFORCabecera,
                    "ValidarSiElPeriodoPuedeSerImportado",
                    null,
                    null,
                    this.periodoDateTimePicker.Text,
                    null,
                    null,
                    null);

                //---- Obtengo los registros contables correspondientes al periodo desde INFOR
                while (i < this.numeroIntentosConsultarRegistrosInfor)
                {
                    try
                    {
                        
                        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ControlPresupuesto.Properties.Settings.INFORConnectionString"].ConnectionString;
                        DataTable table = new DataTable();
                        table.TableName = this.tittle.Text;
                        using (System.Data.Odbc.OdbcConnection conn = new System.Data.Odbc.OdbcConnection(connectionString))
                        {
                            conn.Open();
                            //conn.ConnectionTimeout
                            System.Data.Odbc.OdbcCommand command = conn.CreateCommand();
                            //command.CommandType = CommandType.StoredProcedure;
                            //command.CommandText = "CALL LIBREP.SP_REGISTROS_CONTABLES_AWIL(1" + this.periodoDateTimePicker.Text.Substring(2, 2) + this.periodoDateTimePicker.Text.Substring(4, 2) + "01,"+"1" + this.periodoDateTimePicker.Text.Substring(2, 2) + this.periodoDateTimePicker.Text.Substring(4, 2) + "31)";
                            command.CommandText = "";
                            command.CommandText += "SELECT ";
                            command.CommandText += "     A.A7AKNB AS IdTrans,";
                            command.CommandText += "     A.A7GSNB AS LinLibro,";
                            command.CommandText += "     TRIM(A.A7ASCD) AS DivAdmin,";
                            command.CommandText += "     TRIM(A.A7BYNR) AS NumTrans,";
                            command.CommandText += "     TRIM(A.A7B6CE) AS TipTrans,";
                            command.CommandText += "     TRIM(A.A7KMCD) AS Uni,";
                            command.CommandText += "     TRIM(A.A7CRTU) AS Usu,";
                            command.CommandText += "     TRIM(A.A7KNCD) AS Nat,";
                            command.CommandText += "     A.A7DHVA AS Val,";
                            command.CommandText += "     TRIM(A.A7KOCD) AS Mon,";
                            command.CommandText += "     TRIM(A.A7BANA) AS DesLinea,";
                            command.CommandText += "     TRIM(B.ARDHNA)  AS DesCabec,";
                            command.CommandText += "     A.A7DIVA AS ValMDF,";
                            command.CommandText += "     A.A7CACE AS IdEntid,";
                            command.CommandText += "     TRIM(C.VNAME) AS NomEntid,";
                            command.CommandText += "     A.A7FJDT  AS FecDocum,";
                            command.CommandText += "     A.A7FJDT AS FecEfect,";
                            command.CommandText += "     A.A7CRTD AS FecCreac,";
                            command.CommandText += "     TRIM(B.ARALNA)  AS RefTrans,";
                            command.CommandText += "     TRIM(B.ARYXNA) AS RefOrden ";
                            command.CommandText += "FROM  ";
                            command.CommandText += "    AMFLIBA.YAA7REP A ";
                            command.CommandText += "    inner join  AMFLIBA.YAARREP B on A.A7AKNB = B.ARAKNB ";
                            command.CommandText += "    left join AMFLIBA.VENNAM C on A.A7CACE=C.VNDNR ";
                            command.CommandText += "WHERE ";
                            command.CommandText += "    (";
                            command.CommandText += "        SUBSTRING(A.A7KNCD,1,2) IN ('51','53')";
                            command.CommandText += "        OR";
                            command.CommandText += "        (SUBSTRING(A.A7KNCD,1,2)='79' AND A.A7KMCD<>'105053')";
                            command.CommandText += "    )";
                            command.CommandText += "    AND A.A7KMCD <> '01NA'";
                            command.CommandText += "    AND A.A7KNCD NOT IN ('5330010101','5330030101','5330040101','5330050101','5330060101','5330070101','5330080101','5330090101','5344050101','5344050102','7904070101','7904070103','7904070104','7904070105','7904070106','7904070107','7904070108','7904070109','5120240101','5314050101')";
                            command.CommandText += "    AND A.A7FJDT  BETWEEN 1" + this.periodoDateTimePicker.Text.Substring(2, 2) + this.periodoDateTimePicker.Text.Substring(4, 2) + "01 AND 1" + this.periodoDateTimePicker.Text.Substring(2, 2) + this.periodoDateTimePicker.Text.Substring(4, 2) + "31";
                            command.CommandTimeout = 0;
                            table.Load(command.ExecuteReader());
                            conn.Close();
                        }
                        xml = Utils.get().dataTableToXML(table);
                        break;
                    }
                    catch (Exception)
                    {
                        i++;
                        System.Threading.Thread.Sleep((this.MilisegundosDeEspera <= 0 ? 500 : this.MilisegundosDeEspera));
                    }
                }
                
                //----  Verifico si se consultaron los registros desde INFOR
                if ((i >= this.numeroIntentosConsultarRegistrosInfor))
                {
                    Cursor.Current = Cursors.Default; 
                    MessageBox.Show("No fue posible Obtener los Registros Contables Desde INFOR. \nPor Favor, Intente mas Tarde.");
                    return;
                }
                                
                //---- Guardo la informacion
                this.spRegistroINFORCabeceraTableAdapter.FillBy(
                    this.controlPresupuestoDataSet.spRegistroINFORCabecera,
                    "ImportarRegistrosDesdeINFOR",
                    xml,  //---- Paso los registros importados en formato XML
                    null,
                    this.periodoDateTimePicker.Text,
                    null,
                    null,
                    this.ObservacionesTextBox.Text.Trim());

                //----- ok!!!
                MessageBox.Show("Operacion realizada con Exito!");
                this.FrmRegistrosContablesINFOR_Importar_Load(null, null);

            }
            catch (Exception ex)
            {
                MessageException.show(ex);
            }
            Cursor.Current = Cursors.Default; 
        }
    }
}
